<template>
  <div>
    <!--      页上 搜索框  -->
    <!-- :model="" 绑定数据   -->
    <el-form :inline="true" :model="keyword" ref="searchForm" class="demo-form-inline">
            <el-form-item>
              <el-button type="danger" size="small" @click="deleteBatch" icon="el-icon-delete">删除</el-button>
              <el-button type="warning" size="small" @click="openAddDialog" icon="el-icon-plus">添加</el-button>
            </el-form-item>
      <!--  size="small"输入框大小  clearable输入框清空    placeholder 默认背景提示      -->
      <el-form-item label="品名/SKU" prop="productName">
        <el-input size="small" clearable v-model="keyword.productName" placeholder="品名/SKU"></el-input>
      </el-form-item>
      <el-form-item label="产品品牌" prop="brand">
        <el-input size="small" clearable v-model="keyword.brand" placeholder="请输入产品品牌"></el-input>
      </el-form-item>
      <!--   el-icon-search 发大镜   -->
      <el-form-item>
        <el-button type="primary" size="small" @click="search" icon="el-icon-search">查询</el-button>
        <el-button type="primary" plain size="small" @click="resetSearchFrom('searchForm')" icon="el-icon-refresh">
          重置
        </el-button>
      </el-form-item>
    </el-form>



    <!--  添加/更新对话框  -->
    <el-dialog title="添加对话框" :visible.sync="dialogFormVisible" width="44%">
      <el-form :model="Phone" :rules="PhoneRules" ref="unitMessureRulesForm">
        <el-form-item label="品名/SKU" prop="productName">
          <el-input v-model="Phone.productName" autocomplete="off" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="category">
          <el-input v-model="Phone.category" autocomplete="off" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="品牌名称" prop="brand">
          <el-input v-model="Phone.brand" autocomplete="off" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="购买人姓名" prop="purchaser">
          <el-input v-model="Phone.purchaser" autocomplete="off" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="成交金额" prop="purchaseCost">
          <el-input v-model="Phone.purchaseCost" autocomplete="off" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="购买数量" prop="deliveryDate">
          <el-input v-model="Phone.purchaseQuantity" autocomplete="off" style="width: 300px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!--   点确定触发函数  进行校验 -->
        <el-button type="primary" @click="addUnitMeasure('unitMessureRulesForm')">确 定</el-button>
      </div>
    </el-dialog>


<!--      页中 表格区域-->
<!--    handleSelectionChange处理选项改变-->
<!--      loading 加载中效果    measureList表格数据   handleSelectionChange 复选框会触发函数 需要创建函数-->
    <el-table v-loading="loading" :data="measureList" @selection-change="handleSelectionChange">
      <!--   selection复选框   -->
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户ID" align="center" prop="productId"/>
      <el-table-column label="品名/SKU" align="center" prop="productName"/>
      <el-table-column label="分类" align="center" prop="category"/>
      <el-table-column label="品牌" align="center" prop="brand">

      </el-table-column>
      <el-table-column label="购买人" align="center" prop="purchaser"/>
      <el-table-column label="成交价钱" align="center" prop="purchaseCost">
      </el-table-column>
      <el-table-column label="购买数量" align="center" prop="purchaseQuantity"/>
      <el-table-column label="订单时间" align="center" prop="createdAt"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  页脚 分页区域 -->
    <!--  分页卡片  -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5,10,15,20]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import { getList, delById, delBatch, addMessure, Phone } from '@/api/unit.js'

export default {
  name: 'Unit',
  data() {
    return {
      // 遮罩层
      loading: true, //加载中效果       查询所需变量
      // 储存单位表格数据
      measureList: [],
      primaryUnitList: [], //储存主单位数据
      pageNum: 1,
      pageSize: 5,
      currentPage: 1,  //当前页变量
      total: 0,    //总条数

      keyword: {
        productName: null,   //单位编码
        brand: null    //单位名称
      },
      ids: [],  //定义储存ID

      title: '',
      dialogFormVisible: false,    //对话框默认不可见

      Phone: {
        productid : '',
        productName: '',
        category: '',
        brand: '',
        purchaser: null,
        purchaseCost: null,
        purchaseQuantity: null,
        deliveryDate: null,
        createdAt: null
      },
      PhoneRules:{
        productid:[
          {required: true, message: '用户ID不能为空', trigger: 'blur'},
        ],
        productName:[
          {required: true, message: '产品型号不能为空', trigger: 'blur'},
        ],
        category:[
          {required: true, message: '类型不能为空', trigger: 'blur'},
        ],
        brand:[
          {required: true, message: '品牌不能为空', trigger: 'blur'},
        ],
        purchaser:[
          {required: true, message: '姓名不能为空', trigger: 'blur'},
        ],
        purchaseCost:[
          {required: true, message: '成交不能为空', trigger: 'blur'},
        ],
        purchaseQuantity:[
          {required: true, message: '购买不能为空', trigger: 'blur'},
        ],
      }
    }
  },
  methods: {

    fetchData() {             /*查询 */
      // 获取数据  需要创建unit.js导入
      // 组装查询参数
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,  // 这两个是当前页的信息传递
        productName: this.keyword.productName,
        brand: this.keyword.brand  //这两个是把keyword里面的关键信息传递
      }
      // getList是api/unit.js   开始回调
      getList(params).then(res => {  //res就是R  走到这里就不要判读对错了
        let pageInfo = res.data  //data 就是后端的info 赋值给pageInfo
        //console.log("拿到后端的info pageInfo",pageInfo)
        this.loading = false  //查询完 遮罩关闭
        this.measureList = pageInfo.list  //把pageInfo.list数据赋值给measureList集合
        this.total = pageInfo.total   //取出总条数赋值给total
        //console.log(res.data)
      })
    },

    //查询  模糊搜索
    search() {
      this.fetchData()
    },
    //重置表单
    resetSearchFrom(formName) {
      this.$refs[formName].resetFields()
      this.fetchData()
    },


    /*分页卡片*/
    //页面大小改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()    //页面改变时重新查询数据
      //console.log(`每页 ${val} 条`);
    },
    //页面页码改变时触发
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchData()
      //console.log(`当前页: ${val}`);
    },


    //  添加/更新对话框
    openAddDialog() {
      this.dialogFormVisible = true;
    },



    //添加计量单位  进行效验
    addUnitMeasure(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 在此处执行添加...
          //console.log(this.unitMessure)   测试取出的数据
          addMessure(this.Phone).then(res=>{
            this.fetchData();   //删除成功后查最新数据
            this.$message({  //这是弹窗
              type: 'success',
              message: '添加成功!',
            })
            this.fetchData();   //删除成功后查最新数据          })
          })

        } else {
          console.log('error submit!!');
          return false;
        }
        this.dialogFormVisible = false;  //不管效验是否通过对话框取消
      });
    },




    // 根据ID删除
    handleDelete(row) {
      //console.log(row) //取iD  返回行对象 确认id
      //console.log(row.measureId)//确认Id
      //this.$confirm("是否确认删除单位编号为【"+row.measureId+"】的数据项？")   //弹窗
      this.$confirm("是否确认删除单位编号为" + row.productId + "的数据项？", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {


        /*let parmes ={ //拼接
          key:value
        }*/
        //delById({id:row.measureId})

        //成功之前发请求
        let params = {  //获取参数（拼接）
          id: row.productId   // 键值  键和后端一致  后端为id   值为要删除的
        }
        console.log(params)
        delById(params)  //吊delById  传入ID
          .then(res => {    //返回
            this.$message({  //这是弹窗
              type: 'success',
              message: '删除成功!',
            })
            this.fetchData();   //删除成功后查最新数据
          });

      })
        .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    // 多选框选中数据  可以获得选项行的所有数据
    // 我们需要ID 新建ids存储
    handleSelectionChange(selectionRomArr) {
      this.ids = []   //每次点击置空数组
      //console.log(selectionRomArr)   一行对象
      for (let i = 0; i < selectionRomArr.length; i++) {   //遍历取出id放入ids
        this.ids.push(selectionRomArr[i].productId)     //this.ids取出id
      }
      console.log('ids:', this.ids)  //看看取出的id是否正确
    },
    //批量删除
    deleteBatch() {
      this.$confirm("是否确认删除单位编号为【" + this.ids + "】的数据项？", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {


        let idStr = this.ids.join(",")//join将数组拼接以指定拼接形式拼接  返回一个id字符串
        //console.log("idStr",idStr)  //打印字符串
        //成功之前发请求
        let params = {  //获取参数（拼接）
          ids: idStr

          // 键值  键和后端一致  后端为id   值为要删除的
        }
        /* delBatch({ids : this.ids.join(",") })    //一步到位  上面可以删除
           .then()*/
        delBatch(params)  //吊delById  传入ID

          .then(res => {    //返回
            this.$message({  //这是弹窗
              type: 'success',
              message: '删除成功!',
            })
            this.fetchData();   //删除成功后查最新数据
          });


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

  },

// 生命周期钩子函数(vue对象创建完,自动调用该方法)
  created() {
    this.fetchData()  //抓数据
  }

}

</script>

<style scoped>

</style>
